package internal

import (
	"bytes"
	"github.com/jmoiron/sqlx"
	"github.com/thoas/go-funk"
	"regexp"
	"strings"
	"zt-compute/config"
)

func GetIndexByCode() ([]config.Index, []string) {
	indexes := config.MyConfig.Index
	if len(indexes) == 0 {
		MyLog.Warn("没有配置采集指标")
		return nil, nil
	}
	codes := make([]string, len(indexes))
	codeToIndex := make(map[string]config.Index)
	for i, item := range indexes {
		codes[i] = item.Code
		codeToIndex[item.Code] = item
	}
	var indexesTemp []config.Index
	query, args, err := sqlx.In("SELECT index_id,code,process_id FROM consumer_index WHERE code in (?)", codes)
	query = config.MyConfig.SqlEngine.Rebind(query)
	err = config.MyConfig.SqlEngine.Select(&indexesTemp, query, args...)
	if err != nil {
		MyLog.Error(err)
	}
	var expression bytes.Buffer
	for i := 0; i < len(indexesTemp); i++ {
		if val, ok := codeToIndex[indexesTemp[i].Code]; ok {
			// 将所有表达式合并
			_, _ = expression.WriteString("," + val.Expression)
			indexesTemp[i].Expression = val.Expression
		}
	}
	MyLog.Debug(indexesTemp)
	return indexesTemp, buildTagsArray(expression).([]string)
}

func buildTagsArray(expression bytes.Buffer) interface{} {
	// 去空格
	allExpression := strings.Replace(expression.String(), " ", "", -1)
	// 正则匹配符号 -+*/,
	spaceRe, _ := regexp.Compile(`[\\-\\+\\/\\8,\s]`)
	// 分割，去重，去掉第一个,获取所有要查询的点位
	tags := funk.Tail(funk.Uniq(spaceRe.Split(allExpression, -1)))
	return tags
}
